
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="gin中间件介绍">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>gin中间件介绍 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        gin中间件介绍
      </h1>
      <span>
        
        <time class="time" datetime="2020-08-06T16:00:00.000Z">
        2020-08-07
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <h2 id="gin框架中间件详解"><a href="#gin框架中间件详解" class="headerlink" title="gin框架中间件详解"></a>gin框架中间件详解</h2><p>gin框架涉及中间件相关有4个常用的方法，它们分别是<code>c.Next()</code>、<code>c.Abort()</code>、<code>c.Set()</code>、<code>c.Get()</code>。</p>
<h3 id="中间件的注册"><a href="#中间件的注册" class="headerlink" title="中间件的注册"></a>中间件的注册</h3><p>gin框架中的中间件设计很巧妙，我们可以首先从我们最常用的<code>r := gin.Default()</code>的<code>Default</code>函数开始看，它内部构造一个新的<code>engine</code>之后就通过<code>Use()</code>函数注册了<code>Logger</code>中间件和<code>Recovery</code>中间件：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">Default</span><span class="params">()</span> *<span class="title">Engine</span></span> &#123;</span><br><span class="line">	debugPrintWARNINGDefault()</span><br><span class="line">	engine := New()</span><br><span class="line">	engine.Use(Logger(), Recovery())  <span class="comment">// 默认注册的两个中间件</span></span><br><span class="line">	<span class="keyword">return</span> engine</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>继续往下查看一下<code>Use()</code>函数的代码：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(engine *Engine)</span> <span class="title">Use</span><span class="params">(middleware ...HandlerFunc)</span> <span class="title">IRoutes</span></span> &#123;</span><br><span class="line">	engine.RouterGroup.Use(middleware...)  <span class="comment">// 实际上还是调用的RouterGroup的Use函数</span></span><br><span class="line">	engine.rebuild404Handlers()</span><br><span class="line">	engine.rebuild405Handlers()</span><br><span class="line">	<span class="keyword">return</span> engine</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>从下方的代码可以看出，注册中间件其实就是将中间件函数追加到<code>group.Handlers</code>中：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(group *RouterGroup)</span> <span class="title">Use</span><span class="params">(middleware ...HandlerFunc)</span> <span class="title">IRoutes</span></span> &#123;</span><br><span class="line">	group.Handlers = <span class="built_in">append</span>(group.Handlers, middleware...)</span><br><span class="line">	<span class="keyword">return</span> group.returnObj()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>而我们注册路由时会将对应路由的函数和之前的中间件函数结合到一起：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(group *RouterGroup)</span> <span class="title">handle</span><span class="params">(httpMethod, relativePath <span class="keyword">string</span>, handlers HandlersChain)</span> <span class="title">IRoutes</span></span> &#123;</span><br><span class="line">	absolutePath := group.calculateAbsolutePath(relativePath)</span><br><span class="line">	handlers = group.combineHandlers(handlers)  <span class="comment">// 将处理请求的函数与中间件函数结合</span></span><br><span class="line">	group.engine.addRoute(httpMethod, absolutePath, handlers)</span><br><span class="line">	<span class="keyword">return</span> group.returnObj()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中结合操作的函数内容如下，注意观察这里是如何实现拼接两个切片得到一个新切片的。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> abortIndex <span class="keyword">int8</span> = math.MaxInt8 / <span class="number">2</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(group *RouterGroup)</span> <span class="title">combineHandlers</span><span class="params">(handlers HandlersChain)</span> <span class="title">HandlersChain</span></span> &#123;</span><br><span class="line">	finalSize := <span class="built_in">len</span>(group.Handlers) + <span class="built_in">len</span>(handlers)</span><br><span class="line">	<span class="keyword">if</span> finalSize &gt;= <span class="keyword">int</span>(abortIndex) &#123;  <span class="comment">// 这里有一个最大限制</span></span><br><span class="line">		<span class="built_in">panic</span>(<span class="string">"too many handlers"</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	mergedHandlers := <span class="built_in">make</span>(HandlersChain, finalSize)</span><br><span class="line">	<span class="built_in">copy</span>(mergedHandlers, group.Handlers)</span><br><span class="line">	<span class="built_in">copy</span>(mergedHandlers[<span class="built_in">len</span>(group.Handlers):], handlers)</span><br><span class="line">	<span class="keyword">return</span> mergedHandlers</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>也就是说，我们会将一个路由的中间件函数和处理函数结合到一起组成一条处理函数链条<code>HandlersChain</code>，而它本质上就是一个由<code>HandlerFunc</code>组成的切片：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> HandlersChain []HandlerFunc</span><br></pre></td></tr></table></figure>

<h3 id="中间件的执行"><a href="#中间件的执行" class="headerlink" title="中间件的执行"></a>中间件的执行</h3><p>我们在上面路由匹配的时候见过如下逻辑：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">value := root.getValue(rPath, c.Params, unescape)</span><br><span class="line"><span class="keyword">if</span> value.handlers != <span class="literal">nil</span> &#123;</span><br><span class="line">  c.handlers = value.handlers</span><br><span class="line">  c.Params = value.params</span><br><span class="line">  c.fullPath = value.fullPath</span><br><span class="line">  c.Next()  <span class="comment">// 执行函数链条</span></span><br><span class="line">  c.writermem.WriteHeaderNow()</span><br><span class="line">  <span class="keyword">return</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中<code>c.Next()</code>就是很关键的一步，它的代码很简单：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(c *Context)</span> <span class="title">Next</span><span class="params">()</span></span> &#123;</span><br><span class="line">	c.index++</span><br><span class="line">	<span class="keyword">for</span> c.index &lt; <span class="keyword">int8</span>(<span class="built_in">len</span>(c.handlers)) &#123;</span><br><span class="line">		c.handlers[c.index](c)</span><br><span class="line">		c.index++</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>从上面的代码可以看到，这里通过索引遍历<code>HandlersChain</code>链条，从而实现依次调用该路由的每一个函数（中间件或处理请求的函数）。</p>
<h3 id="c-Set-c-Get"><a href="#c-Set-c-Get" class="headerlink" title="c.Set()/c.Get()"></a>c.Set()/c.Get()</h3><p><code>c.Set()</code>和<code>c.Get()</code>这两个方法多用于在多个函数之间通过<code>c</code>传递数据的，比如我们可以在认证中间件中获取当前请求的相关信息（userID等）通过<code>c.Set()</code>存入<code>c</code>，然后在后续处理业务逻辑的函数中通过<code>c.Get()</code>来获取当前请求的用户。<code>c</code>就像是一根绳子，将该次请求相关的所有的函数都串起来了。</p>

    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#gin框架中间件详解"><span class="toc-text">gin框架中间件详解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#中间件的注册"><span class="toc-text">中间件的注册</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#中间件的执行"><span class="toc-text">中间件的执行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#c-Set-c-Get"><span class="toc-text">c.Set()/c.Get()</span></a></li></ol></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/07/29/Go语言之map的使用/" rel="next" title="Go语言之map的使用">
          Go语言之map的使用
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/08/10/自动编译启动Go程序/" rel="prev" title="自动编译启动Go程序">
            自动编译启动Go程序
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
